package teatime.core.web.interceptor;

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;

import teatime.core.service.manager.ResourceManager;

import net.sf.json.JSONObject;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;


/**
 * 
 * @author Domingo.Gu
 * @since 2008-2-13
 */
public class ResourceInterceptor implements Interceptor {

	private static final long serialVersionUID = 8355088693382540214L;

	private ResourceManager resourceManager;
	private boolean initialized = false;
    private ApplicationContext context;

	public void setResourceManager(ResourceManager resourceManager) {
		this.resourceManager = resourceManager;
	}

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void init() {
		// TODO Auto-generated method stub
	}

	public String intercept(ActionInvocation invocation) throws Exception {
        if (!initialized) {
            ApplicationContext applicationContext = (ApplicationContext) ActionContext.getContext().getApplication().get(
                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            setResourceManager((ResourceManager)applicationContext.getBean("resourceManager"));
            initialized = true;
        }

        if (resourceManager == null)
            return null;

        Map m = resourceManager.getResourceMap();
        JSONObject j = JSONObject.fromObject(resourceManager.getResourceMap());
		invocation.getInvocationContext().put(
				"resource",
				JSONObject.fromObject(resourceManager.getResourceMap())
						.toString());
		String result = null;
		result = invocation.invoke();
		return result;
	}
}